import axios, {
   type AxiosResponse,
   type AxiosRequestConfig,
   type AxiosRequestHeaders,
} from "axios";
import { useUserInfoStore } from "@/stores/userInfo";
import { ElMessage } from "element-plus";

const request = axios.create({
   baseURL: "/api",
   timeout: 20000, // 请求过期时间
});

/* 定义response对象的data接口 */
interface ResponseData<T> {
   code: number;
   data: T;
   message: string;
}

request.interceptors.request.use((config: AxiosRequestConfig) => {
   const userStore = useUserInfoStore();
   let token = userStore.token;
   if (token) {
      (config.headers as AxiosRequestHeaders).token = token;
   }
   return config;
});

// 添加响应拦截器
request.interceptors.response.use(
   (res) => {
      return res.data;
   },
   (err) => {
      return Promise.reject(err);
   }
);

export default request;
